/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.brillien.services.sso.shiro;

import com.vii.brillien.core.component.sso.SubjectPresence;
import com.vii.brillien.core.management.io.IOServices;
import com.vii.brillien.kernel.BrillienException;
import com.vii.brillien.kernel.annotations.PresenceService;
import com.vii.brillien.kernel.annotations.lifecycle.Resident;
import com.vii.brillien.kernel.axiom.sso.Session;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;

import java.util.LinkedList;
import java.util.List;

/**
 * Reference implementation for a specialized SubjectPresence managing Apache Shiro SSO solution 
 */
@PresenceService
@Resident
public class ShiroPresence<R> extends SubjectPresence<R> {

    @Override
    protected void initiate() throws BrillienException {
        try{
            if( configuration.containsKey("iniFile") ){
                Ini ini = Ini.fromResourcePath(
                    IOServices.getResourcePath( this, configuration.get("iniFile") )
                );
                IniSecurityManagerFactory ismf = new IniSecurityManagerFactory(ini);
                SecurityUtils.setSecurityManager(ismf.createInstance());
            }
            else
                throw new BrillienException("Missing Shiro ini file...");
        } catch( BrillienException be){
            throw be;
        } catch( Throwable t){
            throw new BrillienException( t );
        }
    }

    protected Subject getSubject( Session session ){
        return new Subject.Builder().sessionId( session.getId() ).buildSubject();
    }

    protected List<Permission> getPermissions( List<String> permissions ){
        List<Permission> list = new LinkedList<Permission>();

        for (String permission : permissions) {
            list.add( new WildcardPermission( permission ) );
        }

        return list;
    }

    @Override
    protected Session innerAuthenticate( String username, String principal ) throws BrillienException {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.login(new UsernamePasswordToken( username, principal));
        org.apache.shiro.session.Session s = currentUser.getSession(true);
        return new Session( s.getId().toString() );
    }

    @Override
    protected void innerLogout( Session session ) throws BrillienException{
        getSubject( session ).logout();   
    }

    @Override
    protected boolean innerIsAuthenticated(Session session) throws BrillienException {
        Subject subject = getSubject( session );

        if( subject.isAuthenticated() ){
            subject.getSession( true ).touch();
            return true;
        }

        return false;
    }

    @Override
    protected boolean innerHasRole(Session session, String roleIdentifier) throws BrillienException {
        Subject subject = getSubject( session );
        return subject.hasRole( roleIdentifier );
    }

    @Override
    protected boolean innerHasARole(Session session, List<String> roleIdentifiers) throws BrillienException {
        Subject subject = getSubject( session );
        boolean[] bs = subject.hasRoles( roleIdentifiers );
        for (boolean b : bs) {
            if( b )
                return true;
        }
        return false;
    }

    @Override
    protected boolean innerHasRoles(Session session, List<String> roleIdentifiers) throws BrillienException {
        Subject subject = getSubject( session );
        return subject.hasAllRoles( roleIdentifiers );
    }

    @Override
    protected boolean innerHasPermission(Session session, String permission) throws BrillienException {
        Subject subject = getSubject( session );
        return subject.isPermitted( permission );
    }

    @Override
    protected boolean innerHasAPermission(Session session, List<String> permissions) throws BrillienException {
        Subject subject = getSubject( session );
        boolean[] bs = subject.isPermitted( getPermissions( permissions ) );
        for (boolean b : bs) {
            if( b )
                return true;
        }
        return false;
    }

    @Override
    protected boolean innerHasPermissions(Session session, List<String> permissions) throws BrillienException {
        Subject subject = getSubject( session );
        boolean[] bs = subject.isPermitted( getPermissions( permissions ) );
        for (boolean b : bs) {
            if( !b )
                return false;
        }
        return true;
    }

}
